package cn.chendd.feign.httpclient;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.form.spring.SpringFormEncoder;
import feign.jackson.JacksonDecoder;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

/**
 * @author chendd
 */
public class HttpFeignFormDecoder extends JacksonDecoder {

    private ObjectMapper objectMapper;

    public HttpFeignFormDecoder(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException {

        /*if (true) {
            System.out.println("HttpFeignFormDecoder.decode执行默认的form解码");
            return super.decode(response , type);
        }*/

        final Response.Body body = response.body();
        if (body == null) {
            return null;
        }
        final InputStream inputStream = body.asInputStream();
        String value = StreamUtils.copyToString(inputStream , StandardCharsets.UTF_8);
        if (type == String.class) {
            return value;
        }
        //fastjson JSON.parseObject(value , type);
        return this.objectMapper.readValue(value , this.objectMapper.constructType(type));
    }
}
